package Stack;

import java.util.Scanner;

public class ArrayStackDemo {

  public static void main(String[] args) {
    ArrayStack stack = new ArrayStack(4);
    char key = ' ';
    Scanner scanner = new Scanner(System.in);
    boolean loop = true;
    while (loop){
      System.out.println( "s(show):显示栈的数据");
      System.out.println("e(exit):退出程序");
      System.out.println( "a(add):添加数据到栈中");
      System.out.println("g(get):从栈中取出数据");
      key = scanner.next().charAt(0);
      switch (key) {
        case 's':
          stack.list();
          break;
        case 'e':
          scanner.close();
          loop = false;
          break;
        case 'a':
          System.out.println("请输入一个数字");
          int value = scanner.nextInt();
          stack.push(value);
          break;
        case 'g':
          try {
            int res = stack.pop();
            System.out.println("取出的数据" + res + " ");
          }catch (Exception e){
            e.printStackTrace();
          }
          break;
        default:
          break;
      }

    }
    System.out.println("程序退出");

  }
}

class ArrayStack{
  private int maxSize;
  private int top = -1;
  private int[] stack;

  public ArrayStack(int maxSize){
    this.maxSize = maxSize;
    stack = new int[maxSize];
  }
//  判空
  public boolean isEmpty(){
    return top == -1;
  }
//  判满
  public boolean isFull(){
    return top == maxSize-1;
  }
//  出栈
  public int pop(){
    if (isEmpty()){
      throw new RuntimeException("栈空");
    }
    int res = stack[top];
    top--;
    return res;
  }
//  入栈
  public void push(int value){
    if (isFull()){
      System.out.println("满了");
    }
    top++;
    stack[top] = value;
  }
//  显示数据
  public void list(){
    if (isEmpty()){
      System.out.println("空的");
    }
    for (int i = top; i >= 0; i--) {
      System.out.println(stack[i]);
    }
  }
}

